package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.entity.UserSession;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface UserSessionMapper extends BaseMapper<UserSession> {

    @Select("SELECT * FROM user_sessions WHERE user_id = #{userId} AND active = true")
    List<UserSession> findActiveSessionsByUserId(Long userId);

    @Select("SELECT * FROM user_sessions WHERE token = #{token} AND active = true")
    UserSession findByToken(String token);

    @Update("UPDATE user_sessions SET active = false WHERE user_id = #{userId}")
    int invalidateAllUserSessions(Long userId);

    @Update("UPDATE user_sessions SET active = false WHERE token = #{token}")
    int invalidateSession(String token);

    @Update("UPDATE user_sessions SET last_access_time = #{lastAccessTime} WHERE token = #{token}")
    int updateLastAccessTime(String token, LocalDateTime lastAccessTime);

    @Select("SELECT COUNT(*) FROM user_sessions WHERE user_id = #{userId} AND active = true")
    int countActiveSessions(Long userId);
}